package com.lc.qianrenshiye.uitls;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.lc.qianrenshiye.BaseApplication;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2016/12/30.
 */
public class SetTagUtils {

    private Set<String> set;
    private Context context;

    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    public void setTags(Context context) {

        set = new HashSet<>();
        set.add(BaseApplication.BasePreferences.readUserId());

        if (!(set.size() > 0)) {

            MyToast.showToast("标签集合 没有值, 也就是没有用户id", context);

            return;
        }

        this.context = context;
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。

                    BaseApplication.BasePreferences.saveIsSetTag(true);

                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
//            MyToast.showToast(logs, context);
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private String TAG = "设置别名标签";
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
//                    // 调用 JPush 接口来设置别名。
//                    JPushInterface.setAliasAndTags(getApplicationContext(),
//                            (String) msg.obj,
//                            null,
//                            mAliasCallback);

                    JPushInterface.setTags(context, set, mAliasCallback);

                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };


}
